<?php

namespace App\Repositories;

use App\Models\Article as Articles;

class ArticlesRepository extends BaseRepository
{
    public function model()
    {
        return Articles::class;
    }
     /**
     * Date: 2018/4/10
     * @author Tenny
     * @param $article_id
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getArticles($title = false, $time = false, $author = false, $company_id = false, $limit = 15)
    {
        $query = \DB::table('articles');
        if ($title !== false)
        {
            $query->where('articles.title', 'like', '%' . $title . '%');
        }
        if ($time !== false)
        {
            $start_time = date("Y-m-d 00:00:00", strtotime($time));
            $end_time = date("Y-m-d 23:59:59", strtotime($time));
            $query->where('articles.published_at', '>=', $start_time);
            $query->where('articles.published_at', '<=', $end_time);
        }
        if ($author !== false)
        {
            $query->where('users.name', 'like', '%' . $author . '%');
        }
        if ($company_id !== false)
        {
            $query->where('articles.company_id', '=', $company_id);
        }

        $articles = $query
             ->select(['articles.id', 'articles.title', 'articles.cover', 'users.name', 'articles.published_at', 'articles.company_id', 'companies.title as company_name'])
             ->leftJoin('users', 'users.id', '=', 'articles.user_id')
             // 获取公司名称以及id
             ->leftJoin('companies', 'companies.id', '=', 'articles.company_id')
             ->orderBy('articles.published_at', 'desc')
             ->orderBy('articles.id', 'asc')
             ->paginate($limit);
        return $articles;
    }

    /**
     * Date: 2018/4/10
     * @author Tenny
     * @param $article_id
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
   public function getArticlesDetails($article_id)
   {
       $query = \DB::table('articles');
       $articles = $query->select(['articles.id', 'articles.title', 'articles.cover', 'articles.content', 'users.name', 'articles.published_at', 'articles.company_id', 'companies.title as company_name', 'companies.id as company_id'])
           ->leftJoin('users', 'users.id', '=', 'articles.user_id')
           // 获取公司名称以及id
           ->leftJoin('companies', 'companies.id', '=', 'articles.company_id')
           ->where('articles.id', '=', $article_id)
           ->orderBy('articles.published_at', 'desc')
           ->orderBy('articles.id', 'asc')
           ->first();
       return $articles;
   }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}